import sessionStorage from './storage'

var ObjProto = Object.prototype,
  toString = ObjProto.toString;

export let isObjectNormal = function (obj: any) {
  var type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
}

export let isObject = function (obj: any) {
  var type = typeof obj;
  return toString.call(obj) === '[object Object]';
}

export let isFormData = function (obj: any) {
  var type = typeof obj;
  return toString.call(obj) === '[object FormData]';
}

export let isArray = function (obj: any) {
  return toString.call(obj) === '[object Array]';
};

export let isString = function (obj: any) {
  return toString.call(obj) === '[object String]';
};

export let isNumber = function (obj: any) {
  return toString.call(obj) === '[object Number]';
};

export let isDate = function (obj: any) {
  return toString.call(obj) === '[object Date]';
};

export let dataToQs = function (data: any) {
  if (!data) {
    return null;
  }
  if (!isObject(data) && !isArray(data)) {
    throw new Error('toSearchQuery data must be object or array');
  }
  var strs: any = [];
  if (isObject(data)) {
    Object.keys(data).forEach(key => {
      strs.push(`${key}=${data[key]}`);
    });
    return strs.join('&');
  } else {
    data.forEach((d: any) => {
      strs.push(d);
    });
    return strs.join(',');
  }
}

export let dataToFormData = function (data: any) {
  if (!FormData)
    throw new Error('FormData object does not exist');
  var fromData = new FormData();
  if (!data) {
    return fromData;
  }
  if (isObject(data)) {
    data.keys(data).forEach(function (key: any) {
      fromData.append(key, data[key]);
    });
  }
  return fromData;
}

export let dateAdd = function (interval: any, number: any, date: any): any {
  switch (interval) {
    case "y":
      date.setFullYear(date.getFullYear() + number);
      return date;
    case "q":
      date.setMonth(date.getMonth() + number * 3);
      return date;

    case "M":
      date.setMonth(date.getMonth() + number);
      return date;

    case "w":
      date.setDate(date.getDate() + number * 7);
      return date;

    case "d":
      date.setDate(date.getDate() + number);
      return date;

    case "h":
      date.setHours(date.getHours() + number);
      return date;

    case "m":
      date.setMinutes(date.getMinutes() + number);
      return date;

    case "s":
      date.setSeconds(date.getSeconds() + number);
      return date;

    default:
      date.setDate(date.getDate() + number);
      return date;

  }
}

export let dateDifferenceDay = function dateDifferenceDay(sdate: any, edate: any): any {
  // console.log(date)
  if (typeof edate === 'undefined') {
    edate = new Date();
  } else if (!isDate(edate)) {
    edate = new Date(edate)
  }
  if (!isDate(sdate)) {
    sdate = new Date(sdate)
  }
  // console.log(date)
  // console.log(Date.parse(date))
  // console.log(Date.parse(new Date()))
  var timestamp = Date.parse(edate) - Date.parse(sdate)
  timestamp = Math.abs(timestamp)
  // 除以一天的毫秒数（默认时间戳是到毫秒的，就算取到秒级的时间戳后面也带了3个0）
  timestamp = timestamp / (24 * 3600 * 1000);
  // 取整
  timestamp = Math.floor(timestamp);
  return timestamp;
}


export let getQueryString = function (name: any) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};

export let transformRequestQs = function (data: any) {
  if (isFormData(data)) {
    return data;
  }
  if (isObject(data)) {
    return dataToQs(data);
  }
  return data;
}


export let randomWork = function (randomFlag: any, min: any, max: any): any {
  let str = "",
    range = min,
    arr = [
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
      'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
      'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9',
    ];

  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min; // 任意长度
  }
  for (let i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}


export let downloadFile = function (opts: any, body: any) {
  console.log(body)
  opts = Object.assign({}, {
    token: true,
    method: 'post',
    target: '_blank',
    addUrlPrefix: true
  }, opts)

  var token;
  if (typeof opts.token === "boolean") {
    token = opts.token ? sessionStorage.get("token") : "";
  } else if (typeof opts.token === "function") {
    token = opts.token.apply(null)
  } else {
    token = opts.token
  }

  var form = document.createElement('form');
  form.action = opts.addUrlPrefix ? process.env.VUE_APP_Service_API + opts.url : opts.url;
  form.method = opts.method;
  form.target = opts.target;

  if (!!token) {
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'token';
    input.value = token;
    form.appendChild(input);
  }

  if (!!body && Object.keys(body).length > 0) {
    Object.keys(body).forEach(key => {
      var value = body[key];
      if (isArray(value)) {
        value.forEach((v: any) => {
          var input = document.createElement('input');
          input.type = 'hidden';
          input.name = key;
          input.value = v;
          form.appendChild(input);
        })
      } else {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = value;
        form.appendChild(input);
      }
    })
  }

  document.body.appendChild(form)
  form.submit();
  form.remove();
}

export let getFileExt = function (fileName: any) {
  return fileName.split('.').pop().toLowerCase();
}
export let isEmpty = (obj: any): boolean => {
  if (typeof obj == "undefined" || obj == null || obj == "") {
    return true;
  } else {
    return false;
  }
}

export let  getDaysBetween = (dateString1: string, dateString2: string) =>{
  var startDate = Date.parse(dateString1);
  var endDate = Date.parse(dateString2);
  var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
  return days;
}
